package com.tqjc.system.core.threadpool;

import com.tqjc.system.core.util.SpringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author 86195
 * @version 1.0
 * @description 周期性线程池
 * @date 2023/11/30 14:32
 */
public class ScheduledPoolManager {


    private ScheduledPoolManager() {
    }

    private static ScheduledPoolManager me = new ScheduledPoolManager();


    public static ScheduledPoolManager getInstance() {
        return me;
    }


    private Map<String, ScheduledFuture> taskMap = new HashMap<>();


    private ScheduledExecutorService scheduledPool = SpringUtils.getBean("scheduledExecutorService");


    /**
     *  周期性执行任务
     * @param task  任务
     * @param initialDelay  间隔多久开始执行
     * @param period  多久执行一次
     * @param unit   时间单位
     */
    public void scheduledExecute(Runnable task, long initialDelay, long period, TimeUnit unit, String taskId) throws Exception {
        ScheduledFuture future = taskMap.get(taskId);
        if(future != null){
            throw new Exception("周期性任务taskId重复,请重新确认taskId");
        }
        ScheduledFuture<?> scheduledFuture = scheduledPool.scheduleAtFixedRate(task, initialDelay, period, unit);
        taskMap.put(taskId,scheduledFuture);
    }


    public void shutdown(){
        if(scheduledPool != null && !scheduledPool.isShutdown()){
            scheduledPool.shutdown();
        }

    }

    public void shutdownNow(){
        if(scheduledPool != null && !scheduledPool.isShutdown()){
            scheduledPool.shutdownNow();
        }

    }

    public void cancleTask(String taskId){
        ScheduledFuture scheduledFuture = taskMap.get(taskId);
        if(scheduledFuture != null){
            scheduledFuture.cancel(true);
            taskMap.remove(taskId);
        }

    }
}
